package peer.share;

import java.io.File;
import java.util.HashMap;

import peer.Config;
import peer.Core;
import peer.dstdb.LoadingDBThread;
import peer.p2pnet.DBNode;
import peer.p2pnet.DBNodeIdent;
import peer.p2pnet.PubThread;
import peer.p2pnet.PubThread_ReRegAssist;
import peer.p2pnet.RemoveThread;
import peer.tools.Mdb;
import peer.tools.Mdf;
import peer.tools.Pmd52f;

public class ShareFile {
	public File file;
	File mdf;
	public Mdb mdb;
	public HashMap<DBNodeIdent, DBNode> castMemberTable=new HashMap<DBNodeIdent, DBNode>();
	boolean isCastGroupLoaded=false;
	boolean isCastGroupRefreshed=false;
	boolean isActive=false;
	short blockSum;
	PubThread lat;
	PubThread_ReRegAssist lat2;
	RemoveThread ldt;
	public boolean isPub=false;
	public BlockInfo bi;
	static int state_unrun=4;
	static int state_running=5;
	static int state_runned=6;
	int state= state_unrun;
	ShareFile(Mdb mdb,File file1){
		this.mdb=mdb;
		file=file1;
		String mdStr=Pmd52f.byteArrayToHexString(mdb.md);
		mdf=new File(Config.mdfDir+mdStr+".pmd");
		if(!mdf.exists()){
			Mdf mdf=new Mdf(file,Config.mdfDir);
			@SuppressWarnings("unused")
			byte[] md=mdf.creat();
		}
		
		int sum=(int)(file.length()/(512*1024));
		if((mdf.length())%(512*1024)!=0){
			sum+=1;
		}
		if(sum==0){
			sum=1;
		}
		blockSum=(short) sum;
		bi=new BlockInfo(blockSum);
	}
	
	int getState(){
		return state;
	}
	
	
	
	public void runComplete(){
		state=state_runned;
	}
	
	public File getFile(){
		return file;
	}
	
	void pub(){
		state=state_running;
		stopAllThread();
		isPub=true;
		lat=new PubThread(mdb,bi,file.getName(),this);
	}
	
	void pub_ReRegAssist(){
		stopAllThread();
		lat2=new PubThread_ReRegAssist(mdb,bi);
	}
	
	public void remove(boolean isQuit){
		stopAllThread();
		ldt=new RemoveThread(mdb,isQuit);
	}
	
	public void stopAllThread(){
		if(lat!=null){
			if(lat.run){
				lat.stopPub();
			}
		}
		if(lat2!=null){
			if(lat2.run){
				lat2.stopAddThread();
			}
		}
		if(ldt!=null){
			if(ldt.run){
				ldt.stopDelThread();
			}
		}
	}
}
